package com.idea.zd.sys.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

import com.idea.zd.sys.te.PowerHttpClient;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

import com.idea.zd.sys.config.AppConfig;
import com.idea.zd.sys.interceptor.AdminInterceptor;
import com.idea.zd.sys.interceptor.SysLogInterceptor;
import com.idea.zd.sys.model.Admin;
import com.idea.zd.sys.service.AdminService;
import com.idea.zd.sys.service.DictionaryService;
import com.idea.zd.sys.service.PermissionService;
import com.idea.zd.sys.service.RoleService;
import com.idea.zd.sys.util.CommonUtils;
import com.idea.zd.sys.util.MD5Encrypt;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.server.Service;

/**
 * @author y.z
 * 跳转controller
 * to开头
 */
@ControllerBind(controllerKey="/",viewPath="/pages")
public class IndexController extends BaseController {
	private static final Logger log = Logger.getLogger(IndexController.class);
	@Service
	private AdminService adminService;
	@Service
	private PermissionService permissionService;
	@Service
	private DictionaryService dictionaryService;
	@Service
	private RoleService roleService;
	
	
	@Clear(value={AdminInterceptor.class,SysLogInterceptor.class})
	public void index(){
		setAttr("sysName", PropKit.get("sysName"));
		
		if(null != getSessionAttr("admin")){
			redirect("/toIndex");
			return;
		}
		
		
		render("login.html");
	}
	
	/**
	 * 登录
	 * @throws UnknownHostException 
	 */
	@Clear(AdminInterceptor.class)
	public void login(){
		String account = getPara("account");
		String password = getPara("password");
	
		if(StrKit.isBlank(account)||StrKit.isBlank(password)){
			msgParamNull();
		}else{
			
			
			try {
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken token = new UsernamePasswordToken(account, MD5Encrypt.MD5Encode(password));
				//token.setRememberMe(false);
				//ThreadContext.bind(subject);
				
				
				if(!subject.isAuthenticated()){
					subject.login(token);
				}
				Admin admin = (Admin) getSession().getAttribute("admin");
				
				Admin a = new Admin();				
				a.set("id", admin.get("id"));
				a.set("loginnum", admin.getInt("loginnum")+1);
				a.set("lastlogin", new Date());
				a.set("lastloginip", CommonUtils.getIP(getRequest()));
				adminService.update(a);
				msgSuccess();
			} catch (LockedAccountException e) {
				msgSetVal("用户名或密码错误");
	        } catch (AuthenticationException e) {
	        	msgSetVal("用户名或密码错误");
	        }
		}
	}
	
	@Clear(value={AdminInterceptor.class,SysLogInterceptor.class})
	public void getSessionByName(){
		String sName = this.getPara("sName");
		Object object = this.getSessionAttr(sName);
		msgSuccess(object);
	}

	@Clear(value={AdminInterceptor.class,SysLogInterceptor.class})
	public void getAiqiyiUrl(){
		renderJson(PowerHttpClient.Post());
	}
	/**
	 * 首页
	 */
	public void toIndex(){
		Admin admin = getSessionAttr("admin");
		
		Admin a = new Admin();
		
		a.set("type", admin.get("type"));
		a.set("name", admin.get("name"));
		a.set("gender", admin.get("gender"));
		a.set("head_portrait", admin.get("head_portrait"));
		a.set("phone", admin.get("phone"));
		a.set("email", admin.get("email"));
		a.set("description", admin.get("description"));
		a.set("loginnum", admin.get("loginnum"));
		a.set("lastlogin", admin.get("lastlogin"));
		a.set("lastloginip", admin.get("lastloginip"));
		a.set("type", roleService.getById(a.getInt("type")).get("role_name"));
		a.set("gender", dictionaryService.getName("gender", a.getStr("gender")));
		
		if(null == a.get("head_portrait")){
			a.set("head_portrait", "/static/h-ui/images/user.png");
		}
		
		setAttr("admin", a);
		setAttr("menuList", permissionService.getPermissionList(admin));
		Properties props = System.getProperties();
		setAttr("osName", props.getProperty("os.name"));
		setAttr("useName", props.getProperty("user.name"));
		setAttr("port", getRequest().getLocalPort());
		setAttr("serverName", getRequest().getServerName());
		
		try {
			setAttr("addr", InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Long functionTime = new Date().getTime() - AppConfig.startDate;
		setAttr("functionTime", functionTime/1000/60);
		setAttr("filePath", getRequest().getSession().getServletContext().getRealPath("/"));
		setAttr("cpu", Runtime.getRuntime().availableProcessors());
		setAttr("sysName", PropKit.get("sysName"));
		render("index.html");
	}
	
	/**
	 * 退出
	 */
	public void signOut(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		getSession().removeAttribute("admin");
		redirect("/");
	}
	
	
	
	/**
	 * 管理员列表
	 */
	public void toAdmin(){
		render("admin/admin-list.html");
	}

	/**
	 * 新增管理员
	 */
	@RequiresPermissions("toEditAdmin")
	public void toEditAdmin(){
		render("admin/admin-edit.html");
	}

	/**
	 * 图标
	 */
	public void toIcon(){
		render("icon.html");
	}
	
	
}
